package io.renren.modules.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        log.debug("start insert fill ....");
        autoInsertFillDeleted(metaObject);
        autoInsertFillTime(metaObject, "createTime");
        autoInsertFillTime(metaObject, "updateTime");
    }

    private void autoInsertFillTime(MetaObject metaObject, String field) {
        //判断是否具备属性
        boolean hasField = metaObject.hasSetter(field);
        if(hasField){
            log.info("start insert fill "+field+"....");
            this.strictInsertFill(metaObject, field, LocalDateTime.class, LocalDateTime.now());
        }
    }
    private void autoInsertFillDeleted(MetaObject metaObject) {
        //判断是否具备属性
        boolean hasField = metaObject.hasSetter("deleted");
        if(hasField){
            log.info("start insert fill deleted....");
            this.strictInsertFill(metaObject, "deleted", Integer.class,0);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        autoUpdateFillTime(metaObject, "updateTime");
    }

    private void autoUpdateFillTime(MetaObject metaObject, String field) {
        boolean hasField = metaObject.hasSetter(field);
        if(hasField){
        log.debug("start update fill ....");
        this.strictUpdateFill(metaObject, field, LocalDateTime.class, LocalDateTime.now());
        }
    }
}